import React from 'react';
import styled from 'styled-components';
import { FormattedMessage } from 'react-intl';
import PropTypes from 'prop-types';
import { ShadowWhite, Black, GrayLight4 } from 'style/Color';
import { Bold } from 'style/Weight';
import Table from 'widget/Table';
import EmptyPage from 'widget/EmptyPage';

const Root = styled.div`
  position: relative;
  padding: 10px;
  z-index: 10;
`;

const Styles = styled.div`
  border: 1px solid ${GrayLight4};
  text-align: center;
  overflow: scroll;
  font-size: 12px;
  color: ${Black};

  .table {
    display: inline-block;
    border-spacing: 0;

    .thead .tr {
      font-weight: ${Bold};
    }

    .tbody .tr {
      cursor: pointer;
      font-weight: ${Bold};
      :last-child {
        .td {
          border-bottom: 0;
        }
      }
      :hover {
        background-color: ${ShadowWhite};
      }
    }

    .th,
    .td {
      margin: 0;
      padding: 0.5rem;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
      border-right: 1px solid ${GrayLight4};
      border-bottom: 1px solid ${GrayLight4};

      ${'' /* In this example we use an absolutely position resizer,
       so this is required. */}
      position: relative;

      :last-child {
        border-right: 0;
      }

      ${'' /* The resizer styles! */}

      .resizer {
        transition: all 0.2s ease-in-out;
        display: inline-block;
        width: 2px;
        height: 100%;
        position: absolute;
        right: 0;
        top: 0;
        transform: translateX(50%);
        z-index: 1;

        &.isResizing {
        }
      }

      :hover {
        .resizer {
          background: ${GrayLight4};
        }
      }
    }
  }
`;

const TableColumns = ({ name, data, onSelect }) => {
  if (data.length === 0) {
    return (
      <EmptyPage>
        <FormattedMessage id="nodata" />
      </EmptyPage>
    );
  }

  const columns = React.useMemo(
    () => [
      {
        Header: name,
        columns: Object.keys(data[0]).map(key => {
          return { Header: key, accessor: key };
        })
      }
    ],
    []
  );

  return (
    <Root>
      <Styles>
        <Table columns={columns} data={data} onSelect={onSelect} />
      </Styles>
    </Root>
  );
};

TableColumns.propTypes = {
  name: PropTypes.string.isRequired,
  // eslint-disable-next-line react/forbid-prop-types
  data: PropTypes.array.isRequired,
  onSelect: PropTypes.func.isRequired
};

export default TableColumns;
